import { Form, Button, Col, Input, Popover, Progress, Row, Select, message, Checkbox } from 'antd';
import React, { useState, useEffect } from 'react';
import { connect, FormattedMessage, formatMessage } from 'umi';

import styles from './style.less';
import request from "@/utils/request";

const UserRegister = ({ submitting, dispatch, userRegister }) => {
  let interval;
  const [form] = Form.useForm();
  const [initialValues,setInitialValues] = useState({})
  const [authorityValues,setAuthorityValues] = useState({})
  const [updatePassword,setUpdatePassword] = useState(false)
  const authoritys = []
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const tailFormItemLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 16,
        offset: 8,
      },
    },
  };


  useEffect(() => {
    if (!userRegister) {
      return;
    }
    if (typeof userRegister.Msg === 'undefined') {
      return;
    }
  }, []);
  useEffect(
    () => () => {
      clearInterval(interval);
    },
    []
  );

  useEffect(
    ()=>{
      const cilenetId = getQueryVariable("clientId")
      const updatePassword = getQueryVariable("updatePassword") || false
      setUpdatePassword(updatePassword)
      if (cilenetId) {
        request(`/api/client/getByClientId?ClientId=${cilenetId}`).then(res=>{
          if (res.Code != 0 ){
            message.error(res.Msg);
          }else{
            form.setFieldsValue(res.Data)
            setInitialValues(res.Data)
          }
        })
      }

      request(`/api/client/getAuthority`).then(res=>{
        if (res.Code != 0 ){
          message.error(res.Msg);
        }else{
          setAuthorityValues(res.Data)
        }
      })

    }
  ,[])

  const onFinish = values => {
    {
      initialValues.ClientId ?
        dispatch({
          type: 'userRegister/update',
          payload: {...{ClientId:getQueryVariable("clientId")},...values},
        })
    :
      dispatch({
        type: 'userRegister/submit',
        payload: {...values},
      });
    }

  };

  function getQueryVariable(variable)
  {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      if(pair[0] == variable){return pair[1];}
    }
    return(false);
  }


  return (
    <div className={styles.main}>
      <h3>
        { initialValues.ClientId ? "更新" : "注册"}
      </h3>
      <Form  {...formItemLayout} form={form} name="UserRegister" onFinish={onFinish}>

        { initialValues.ClientId ?
          <Form.Item
          name="ClientId"
          label="用户ID"
          hidden={true}
          >
          <Input disabled={true} />
          </Form.Item>
          :
          <></>}
        <Form.Item
          name="Name"
          label="账号"
          rules={[
            {
              required: true,
              message: '请输入账号',
            },
          ]}
        >
          <Input disabled={initialValues.ClientId ?true:false} />
        </Form.Item>
        { !initialValues.ClientId  ?  <>
        <Form.Item
          name="Password"
          label="密码"
          rules={[
            {
              required: true,
              message: "请输入密码！",
            },
          ]}
          hasFeedback
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="Confirm"
          label="确认密码"
          dependencies={["Password"]}
          hasFeedback
          rules={[
            {
              required: true,
              message: "请确定你的密码！",
            },
            ({ getFieldValue }) => ({
              validator(rule, value) {
                if (!value || getFieldValue("Password") === value) {
                  return Promise.resolve();
                }
                return Promise.reject(
                  "您输入的两个密码不匹配!"
                );
              },
            }),
          ]}
        >
          <Input.Password />
        </Form.Item>

        </> : null}


        { updatePassword  ?  <>
          <Form.Item
            name="Password"
            label="密码"
            rules={[
              {
                required: true,
                message: "请输入密码！",
              },
            ]}
            hasFeedback
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="Confirm"
            label="确认密码"
            dependencies={["Password"]}
            hasFeedback
            rules={[
              {
                required: true,
                message: "请确定你的密码！",
              },
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue("Password") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(
                    "您输入的两个密码不匹配!"
                  );
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>

        </> : null}

        {updatePassword?<></>:
          <Form.Item
            name={"Authority"}
            label="权限"
            rules={[
              {
                required: true,
                message: '请选择权限',
              },
            ]}
          >
            <Checkbox.Group style={{ width: '100%' }} >
              <Row>

                {authorityValues?
                  Object.keys(authorityValues).map(function(v){

                    return (
                      <Col span={10}>
                        <Checkbox value={v}>{authorityValues[v]}</Checkbox>
                      </Col>
                    )
                  })
                  :null}

              </Row>
            </Checkbox.Group>
          </Form.Item>}


        <Form.Item {...tailFormItemLayout}>
          <Button
            size="large"
            loading={submitting}
            className={styles.submit}
            type="primary"
            htmlType="submit"
          >
            { initialValues.ClientId ? "更新" : "注册"}
              </Button>

        </Form.Item>



      </Form>
    </div>
  );
};

export default connect(({ userRegister, loading }) => ({
  userRegister,
  submitting: loading.effects['userRegister/submit'],
}))(UserRegister);
